package top.psjj.news.web;

import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;
import top.psjj.news.po.TLink;
import top.psjj.news.service.LinkService;
import top.psjj.news.service.impl.LinkServiceImpl;
import top.psjj.news.utils.ServiceProxyFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Auther:小陈的Java
 */
@WebServlet("/link")
public class LinkServlet extends BasicServlet {
    private String mainUrl = "/WEB-INF/jsp/main/mainTemp.jsp";
    private String baseUrl = "./link/";
    private LinkService linkService = (LinkService) ServiceProxyFactory.getService(LinkServiceImpl.class);

    public void list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        List<TLink> list = linkService.queryAll();
        req.setAttribute("list", list);
        req.setAttribute("mainPage", baseUrl + "linkList.jsp");
        req.getRequestDispatcher(mainUrl).forward(req, resp);
    }

    public void addUI(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setAttribute("mainPage", baseUrl + "linkSave.jsp");
        req.getRequestDispatcher(mainUrl).forward(req, resp);
    }

    public void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Map<String, String[]> parameterMap = req.getParameterMap();
        TLink link = new TLink();
        BeanUtils.populate(link, parameterMap);
        if (link.getId() == null || link.getId() == 0) {
            //添加
            linkService.add(link);
        } else {
            //修改
            linkService.update(link);
        }
        resp.sendRedirect(req.getContextPath() + "/link?method=list");

    }

    public void updateUI(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        int id = Integer.parseInt(req.getParameter("id"));
        TLink link = linkService.queryLinkById(id);
        req.setAttribute("link", link);
        req.setAttribute("mainPage", baseUrl + "linkSave.jsp");
        req.getRequestDispatcher(mainUrl).forward(req, resp);
    }

    public void del(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        int id = Integer.parseInt(req.getParameter("id"));
        linkService.del(id);
        resp.sendRedirect(req.getContextPath() + "/link?method=list");
    }
    //链接列表
    public void linkList (HttpServletRequest req,HttpServletResponse resp) throws Exception{
        //1.设置响应数据格式
        resp.setContentType("application/json;charset=utf-8");
        //2.获得链接列表
        List<TLink> list = linkService.queryAll();
        //3.将数据转为json数据
        Gson gson = new Gson();
        String result = gson.toJson(list);
        //4.响应数据
        resp.getWriter().print(result);
    }
}
